package com.dmai.capacity.platform.user.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.dmai.capacity.platform.common.dto.PageResult;
import com.dmai.capacity.platform.common.dto.ResponseEntity;
import com.dmai.capacity.platform.user.model.SysOrganization;
import com.dmai.capacity.platform.user.pojo.TreeVo;
import com.dmai.capacity.platform.user.pojo.response.InstitutionVO;
import com.dmai.capacity.platform.user.service.ISysInstitutionService;
import com.dmai.capacity.platform.user.service.ISysOrganizationService;
import org.apache.commons.collections.list.TreeList;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.security.access.prepost.PreAuthorize;

import javax.persistence.criteria.CriteriaBuilder;
import javax.validation.Valid;

/**
 * 组织架构表
 *
 * @author
 * @email
 * @date 2024-05-22 13:36:20
 */
@RestController
public class SysOrganizationController {

    @Autowired
    private ISysOrganizationService orgService;

    @Autowired
    private ISysInstitutionService institutionService;

    /**
     * 列表
     */
    @GetMapping("/organizations/list")
//    @PreAuthorize("hasAnyAuthority('sys_organization:sysorganization:list')")
    public PageResult list(@RequestParam Map<String, Object> params) {
        PageResult pageResult = orgService.pageAll(params);
        return pageResult;
    }

    /**
     * 层级结构
     *
     * @param parentId
     * @return
     */
    @GetMapping("/organizations/tree")
//    @PreAuthorize("hasAnyAuthority('sys_organization:sysorganization:list')")
    public ResponseEntity<List<TreeVo>> tree(@RequestParam(value = "parentId", required = false) String parentId,
                                             @RequestParam(value = "recursion", defaultValue = "0") Integer recursion,
                                             @RequestParam(value = "loadAll", defaultValue = "0") Integer loadAll) {
        Map<String, Object> params = new HashMap<>();
        params.put("status", 1);
        if (0 == recursion) {
            params.put("parentId", parentId);
        }
        params.put("loadAll", loadAll);
        List<SysOrganization> companys = orgService.findAll(params);
        List<TreeVo> treeList = new TreeList();
        companys.forEach(m -> {
            TreeVo node = new TreeVo();
            node.setId(m.getId());
            node.setText(m.getName());
            node.setTitle(m.getName());
            node.setValue(m.getId().toString());
            node.setShowcheck(false);
            node.setCheckstate(0);
            if (StringUtils.isEmpty(m.getParentId())) {
                node.setIsexpand(true);
            } else {
                node.setIsexpand(false);
            }
            node.setComplete(false);
            node.setParentId(m.getParentId());
            treeList.add(node);
        });

        return ResponseEntity.succeed(TreeVo.RecursiveBuilder(treeList, "-1"));
    }

    /**
     * 层级结构
     *
     * @param parentId
     * @return
     */
    @GetMapping("/organizations/tree2")
//    @PreAuthorize("hasAnyAuthority('sys_organization:sysorganization:list')")
    public ResponseEntity<List<TreeVo>> tree2(@RequestParam(value = "parentId", required = false) String parentId,
                                              @RequestParam(value = "recursion", defaultValue = "0") Integer recursion,
                                              @RequestParam(value = "loadAll", defaultValue = "0") Integer loadAll) {
        Map<String, Object> params = new HashMap<>();
        params.put("status", 1);
        if (0 == recursion) {
            params.put("parentId", parentId);
        }
        params.put("loadAll", loadAll);
        List<SysOrganization> companys = orgService.findAll(params);
        List<TreeVo> treeList = new TreeList();
        companys.forEach(m -> {
            TreeVo node = new TreeVo();
            node.setId(m.getId());
            node.setText(m.getName());
            node.setTitle(m.getName());
            node.setValue(m.getId().toString());
            node.setShowcheck(false);
            node.setCheckstate(0);
            if (StringUtils.isEmpty(m.getParentId())) {
                node.setIsexpand(true);
            } else {
                node.setIsexpand(false);
            }
            node.setComplete(false);
            node.setParentId(m.getParentId());
            treeList.add(node);
        });
        List<TreeVo> treeVos = TreeVo.RecursiveBuilder(treeList, "-1");

        checkHasInstitution(treeVos);

        return ResponseEntity.succeed(treeVos);
    }


    //判断区县是否包含机构
    private void checkHasInstitution(List<TreeVo> trees) {
        Map<String,Object> param = new HashMap<>();
        for (TreeVo vo : trees) {
            if (!vo.getHasChildren()) {
                param.put("examVenues",vo.getValue());
                Integer count = institutionService.count(param);
                if(count>0) {
                    vo.setHasChildren(true);
                }
            } else {
                checkHasInstitution(vo.getChildNodes());
            }
        }
    }


    /**
     * 查询单条记录
     */
    @GetMapping("/organizations/{id}")
//    @PreAuthorize("hasAnyAuthority('sys_organization:sysorganization:list')")
    public ResponseEntity findById(@PathVariable(value = "id") String id) {
        return ResponseEntity.succeed(orgService.findById(id));
    }

    /**
     * 保存
     */
    @PostMapping("/organizations")
//    @PreAuthorize("hasAnyAuthority('sys_organization:sysorganization:save')")
    public ResponseEntity save(@RequestBody @Valid SysOrganization org) {
        orgService.save(org);
        return ResponseEntity.succeed("操作成功");
    }

    /**
     * 修改
     */
    @PutMapping("/organizations")
//    @PreAuthorize("hasAnyAuthority('sys_organization:sysorganization:save')")
    public ResponseEntity update(@RequestBody @Valid SysOrganization org) {
        orgService.update(org);
        return ResponseEntity.succeed("操作成功");
    }


    /**
     * 删除
     */
    @DeleteMapping("/organizations/{id}")
//    @PreAuthorize("hasAnyAuthority('sys_organization:sysorganization:delete')")
    public ResponseEntity delete(@PathVariable(value = "id") String id) {
        orgService.delete(id);
        return ResponseEntity.succeed("操作成功");
    }

}
